package com.hoongs.v1.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hoongs.v1.entity.Cart;
import com.hoongs.v1.service.CartService;
import com.hoongs.v1.utils.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;

@RestController
@RequestMapping("/cart")
@Validated
public class CartController {

    @Resource
    private CartService cartService;

    @GetMapping("/selectListByUser")
    public Result selectListByUser(@RequestHeader("token") String token) {
        return cartService.selectListByUser(token);
    }

    @PostMapping("/updateListByUser")
    public Result updateListByUser(ArrayList<Cart> list, @RequestHeader("token") String token) {
        return cartService.updateListByUser(list, token);
    }

    @PostMapping("/updateCartByUser")
    public Result updateCartByUser(String id, String productId, BigDecimal number, @RequestHeader("token") String token) {
        return cartService.updateCartByUser(id, productId, number, token);
    }

    @PostMapping("/removeFromCart")
    public Result removeFromCart(String id, @RequestHeader("token") String token) {
        return cartService.removeFromCart(id, token);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result add(@Validated Cart cart, BindingResult bindingResult) {
        String res = Result.resultMsg(bindingResult);
        return StringUtils.isNotBlank(res) ? Result.opError(res) : cartService.add(cart);
    }

    @PostMapping("/remove")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result remove(String id) {
        return cartService.remove(id);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result update(Cart cart) {
        return cartService.update(cart);
    }


    @GetMapping("/selectPageList")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result selectPageList(Integer page, Integer size, String userId, String userName) {
        return cartService.selectPageList(page, size, userId, userName);
    }

}
